import React, {useEffect, useState} from 'react';
import { Form, Button ,Input,Modal,message} from 'antd';
const FormItem = Form.Item;
import {getCheckCode,updatePwd} from '../service';

const layoutCol = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const CheckAuth = (props) => {
  const { onSubmit, onCancel, loading,status,visible} = props;
  const [form] = Form.useForm();
  const [title,setTitle] = useState(null);
  const [flag,setFlag] = useState(false);
  const [updateVisible,setUpdateVisible] = useState(false);
  const [codeStatus,setCodeStatus] = useState(true);
  const [count,setCount] = useState(60);

  useEffect(() => {
    if(visible && status){
      setTitle(status === 'noEntity' ? <div style={{color:'red'}}>首次登录，请设置全新的二级密码</div> : '输入二级密码');
    }
  }, [visible]);

  const forget = () => {
    setFlag(true);
  };

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...fieldsValue});
  };

  const getCode = () => {
    getCheckCode().then(res => {
      if(res.flag){
        setCodeStatus(false);
        message.success('验证码发送成功，请查看企微信息！');
        let temp = 60;
        const timer = setInterval(() => {
          if (temp === 0) {
            clearInterval(timer);
            setCodeStatus(true);
            temp = 60;
          }else {
            setCount(temp --);
          }
        }, 1000);
      }else{
        message.error(`验证码发送失败：`+res.error);
      }
    });
  };

  const updatePassword = async () =>{
    const fieldsValue = await form.validateFields();
    setUpdateVisible(true);
    updatePwd(fieldsValue).then(res => {
      if(res.flag){
        form.resetFields();
        message.success('密码修改成功！');
        setFlag(false);
      }else{
        message.error(`修改失败：`+res.error);
      }
      setUpdateVisible(false);
    });
  };

  const renderFooter = () => {
    return (
      <>
        {flag ?
          <> <Button onClick={() => setFlag(false)}>返回</Button> <Button type="primary" onClick={() => updatePassword()} loading={updateVisible}>确认修改</Button> </>:
          <> <Button onClick={() => onFormCancel()}>取消</Button><Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button></>
        }
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width={'30%'}
      destroyOnClose
      centered
      title={flag ? '忘记密码' : title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form form={form} style={{ paddingTop: '24px' }}  {...layoutCol} layout="horizontal">
        <FormItem style={{display: flag ? 'flex' : 'none'}} label="验证码" required={true}>
          <FormItem name="checkCode" noStyle rules={[{required: flag, message: '验证码不能为空！'}]}>
            <Input placeholder="请输入企微验证码" style={{width:'70%'}}/>
          </FormItem>
          <Button disabled={!codeStatus} type="link" onClick={() => getCode()}>{codeStatus ? '获取验证码' : count + '秒'}</Button>
        </FormItem>
        <FormItem name="pwd" label="二级密码" rules={[{required: true, message: '二级密码不能为空！'}]} extra={status === 'noEntity' ? null : <Button disabled={flag} onClick={forget} style={{padding: '4px 0px'}} type="link">忘记密码</Button>}>
          <Input.Password placeholder="请输入二级密码" autoComplete="new-password"/>
        </FormItem>
      </Form>
    </Modal>
  )
};

export default(CheckAuth);
